package com.ccb.health.controller;

import com.ccb.health.entity.User;
import com.ccb.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 请求到首页
     * @return
     */
    @GetMapping()
    public String getIndex(){
        return "/index";
    }

    /**
     * 登录请求
     * @return
     */
    @PostMapping("/login")
    public String login(User user, ModelMap mmap, HttpSession session){
        List<User> users = userService.selectUser(user);
        User user0 = users.size() == 0 ? null : users.get(0);
        // 如果用户存在
        if(user0 != null){
            if(user0.getState()) {
                session.setAttribute("user", user0);
                // 判断是否是管理员
                if (user0.getIsAdmin()) {
                    return "redirect:/admin";
                }
                return "redirect:/user";
            }
            // 用户被禁用，请联系管理员解封
            String msg = "用户被禁用，请联系管理员解封";
            mmap.addAttribute("msg", msg);
            return "/index";
        }
        // 用户不存在
        String msg = "用户名或密码错误";
        mmap.addAttribute("msg", msg);
        return "/index";
    }
}
